package com.epfresh.api.update;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat.Builder;
import android.support.v4.content.FileProvider;
import android.util.Log;

import com.epfresh.api.R;
import com.epfresh.api.helper.ApplicationHelper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadService extends IntentService {

    private static final int BUFFER_SIZE = 10 * 1024; // 8k ~ 32K
    private static final String TAG = "DownloadService";
    private NotificationManager mNotifyManager;
    private Builder mBuilder;

    Context context = this;

    private File fileApk;

    public DownloadService() {
        super("DownloadService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        /*justTry*/

        ApplicationHelper.getInstance().isDownloadApk = true;
        mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("epfresh", "LOCATION",NotificationManager.IMPORTANCE_DEFAULT);
            mNotifyManager.createNotificationChannel(channel);
            mBuilder = new Builder(context, "epfresh");
        }else {
            mBuilder = new Builder(context);
        }
        String appName = getString(getApplicationInfo().labelRes);
        int icon = getApplicationInfo().icon;

        mBuilder.setContentTitle(appName).setSmallIcon(icon);
        String urlStr = intent.getStringExtra(Constants.APK_DOWNLOAD_URL);
        InputStream in = null;
        FileOutputStream out = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

//			urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(false);
            urlConnection.setConnectTimeout(30 * 1000);
            urlConnection.setReadTimeout(30 * 1000);
            urlConnection.setRequestProperty("Connection", "Keep-Alive");
//			urlConnection.setRequestProperty("Charset", "UTF-8");
//			urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");

            urlConnection.connect();
            long bytetotal = urlConnection.getContentLength();
            long bytesum = 0;
            int byteread = 0;
            in = urlConnection.getInputStream();
            File dir = StorageUtils.getCacheDirectory(this);
            String apkName = urlStr.substring(urlStr.lastIndexOf("/") + 1, urlStr.length());
            File apkFile = new File(dir, apkName);
            this.fileApk = apkFile;
            out = new FileOutputStream(apkFile);
            byte[] buffer = new byte[BUFFER_SIZE];

            int oldProgress = 0;

            while ((byteread = in.read(buffer)) != -1) {
                bytesum += byteread;
                out.write(buffer, 0, byteread);

                int progress = (int) (bytesum * 100L / bytetotal);
                // 如果进度与之前进度相等，则不更新，如果更新太频繁，否则会造成界面卡顿
                if (progress != oldProgress) {
                    updateProgress(progress);
                }
                oldProgress = progress;
            }
            // 下载完成
            mBuilder.setContentText(getString(R.string.download_success)).setProgress(0, 0, false);

            //如果没有设置SDCard写权限，或者没有sdcard,apk文件保存在内存中，需要授予权限才能安装
            String[] command = {"chmod", "777", apkFile.toString()};
            ProcessBuilder builder = new ProcessBuilder(command);
            builder.start();

/*            installAPKIntent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            installAPKIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);*/
            //installAPKIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //installAPKIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

/*            if(Build.VERSION.SDK_INT>=24) { //判读版本是否在7.0以上
                //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件

                Uri apkUri =
                        FileProvider.getUriForFile(context, /"com.epfresh.supplier", apkFile);
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                installAPKIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                installAPKIntent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            }else{
                installAPKIntent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                installAPKIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }*/
            Log.e("service_install","service_install");

            install(apkFile);
//			mBuilder.setContentIntent(pendingIntent);
//			Notification noti = mBuilder.build();
//			noti.flags = android.app.Notification.FLAG_AUTO_CANCEL;
//			mNotifyManager.notify(0, noti);
            mNotifyManager.cancel(0);
            ApplicationHelper.isDownloadApkFail = false;
        } catch (Exception e) {
            Log.e(TAG, "download apk file error", e);
            e.printStackTrace();

            updateError();
        } finally {
            ApplicationHelper.getInstance().isDownloadApk = false;
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public void install(File file) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if(Build.VERSION.SDK_INT>=24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
/*            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                //注意这个是8.0新API,直接跳转到允许安装位置来源的页面
                intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, uri);
            }else {*/
                Uri apkUri =
                        FileProvider.getUriForFile(context, ApplicationHelper.getInstance().getFileProvider(), file);

                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
           // }
        }else{
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");



            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);




        }
        startActivity(intent);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }


    private void updateProgress(int progress) {
        //"正在下载:" + progress + "%"
        mBuilder.setContentText(this.getString(R.string.download_progress, progress)).setProgress(100, progress, false);
        //setContentInent如果不设置在4.0+上没有问题，在4.0以下会报异常
        PendingIntent pendingintent = PendingIntent.getActivity(this, 0, new Intent(), PendingIntent.FLAG_CANCEL_CURRENT);
        mBuilder.setContentIntent(pendingintent);
        mNotifyManager.notify(0, mBuilder.build());
        try {
            if (ApplicationHelper.updateApkDialogActivity != null) {
                ApplicationHelper.updateApkDialogActivity.updateProgress(progress);
                if (progress > 99){
                    ApplicationHelper.updateApkDialogActivity.setFileApk(fileApk);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updateError() {
        mBuilder.setContentText("下载失败").setProgress(0, 0, false);
        PendingIntent pendingintent = PendingIntent.getActivity(this, 0, new Intent(), PendingIntent.FLAG_CANCEL_CURRENT);
        mBuilder.setContentIntent(pendingintent);
        mNotifyManager.notify(0, mBuilder.build());
        ApplicationHelper.isDownloadApkFail = true;
        try {
            if (ApplicationHelper.updateApkDialogActivity != null) {
                ApplicationHelper.updateApkDialogActivity.updateProgress(-1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
